var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var compression = require('compression'); // 压缩响应
var bodyParser = require('body-parser');
var siofu = require('socketio-file-upload');


var index = require('./routes/index');
var users = require('./routes/users');


var app = express();


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');


// 对程序因意外错误而不得不关闭服务器的处理
app.use(function (req,res,next) {
    // 对请求创建一个域
    var domain = require('domain').create();
    // 处理这个域中的错误
    domain.on('error',function (err) {
        console.error('DOMAIN ERROR CAUGHT\n',err.stack);
        try {
            // 在5秒内进行故障保护关机
            setTimeout(function () {
                console.error('Failsafe shutdown');
                process.exit(1);
            },5000);
            // 从集群中断开
            var worker = require('cluster').worker;
            if (worker) {
                worker.disconnect();
            }
            // 停止接受新请求
            server && server.close();

            try {
                // 尝试使用Express的错误路由
                next(err);
            } catch(err) {
                // 如果Express错误路由失效，尝试返回普通文本响应
                console.error('Express error mechanism faild.\n',err.stack);
                res.statusCode = 500;
                res.setHeader('content-type','text/plain');
                res.end('Server Error.');
            }
        } catch (err) {
            console.error('Unable to send 500 response.\n',err.stack);
        }
    });

    // 向域中添加请求和响应对象
    domain.add(req);
    domain.add(res);

    // 执行域中剩余的请求链
    domain.run(next);
});

// 应用级中间件
app.use(compression()); // 启用gzip压缩

app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
if (app.get('env') !== 'production') {
    app.use(logger('dev'));
}
app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(siofu.router); // 文件上传的socket处理

/**
 * Routers setting
 * */
/*app.use('/', index);
app.use('/users', users);*/
app.get('/', function (req, res) {
    res.status(200).send('Welcome to use the based websocket file upload service.');
});
app.get('/file-upload', function (req, res) {
    res.sendFile(__dirname + '/public/index.html');
});



// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});




module.exports = app;
